import express from 'express'
import boom from '@hapi/boom';
import { validationResult, Result, ValidationError } from 'express-validator';

import { querySql } from '../db/mysql';
import { CODE_ERROR, CODE_SUCCESS } from '../utils/constant';

export function getCarousel(req: express.Request, res: express.Response, next) {
    const queryStr:string = `select * from carousel`
    querySql(queryStr).then(data => {
        res.json({
            code: CODE_SUCCESS,
            data,
            msg: '成功'
        })
    }).catch(err => {
        const error = new Error(err)
        next(boom.boomify(error, {
            statusCode: 501,
            message: '数据库异常'
        }))
    })

}

// 保存轮播图
export function saveCarousel(req: express.Request, res: express.Response, next:express.NextFunction) {
    
    const errors:Result<ValidationError> = validationResult(req);
    
    if(!errors.isEmpty()){
        const msgObj = errors.array({onlyFirstError: true})[0];
        const msg =  `缺失${msgObj.param},请检查`
        next(boom.badRequest(msg))
        return
    }
    // 单条数据插入
    const saveSql:string= `insert into carousel set ?`
    const {title, subTitle, imgSrc, path} = req.body
    querySql(saveSql, {title, subTitle, imgSrc, path}).then(data => {
        res.json({
            code: CODE_SUCCESS,
            msg: '保存成功'
        })
    }).catch(err => {
        const error=new Error(err)
        next(boom.boomify(error, {
            statusCode: 501,
            message: '数据库异常'
        }))
    })
}   

// 更新轮播图
export function updateCarousel(req: express.Request, res: express.Response, next: express.NextFunction){
    const errors: Result<ValidationError> = validationResult(req)
    if(!errors.isEmpty()){
        const msgObj = errors.array({onlyFirstError: true})[0];
        const msg =  `缺失${msgObj.param},请检查`
        next(boom.badRequest(msg))
        return
    }
    const {id} = req.params
    const {title, subTitle, imgSrc, path}=req.body
    const updateSql:string = `update carousel set ? where id=${id}`
    querySql(updateSql, {title, subTitle, imgSrc, path}).then(data => {
        res.json({
            code: CODE_SUCCESS,
            msg: '更新成功'
        })
    }).catch(err => {
        const error = new Error(err)
        next(boom.boomify(error, {
            statusCode: 501,
            message: '数据库异常'
        }))
    })
}

// 删除轮播图
export function delCarousel(req:express.Request, res:express.Response, next: express.NextFunction){
    const {id} = req.params
    const delSql:string=`delete from carousel where id=${id}`
    querySql(delSql).then(data => {
        res.json({
            code: CODE_SUCCESS,
            msg: '删除成功'
        })
    }).catch(err => {
        const error = new Error(err)
        next(boom.boomify(error, {
            statusCode: 501,
            message: '数据库异常'
        }))
    })
}